package com.sunlands.deskmate.message.handler.receiver.impl;

import com.sunlands.deskmate.client.UserFriendService;
import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.message.enums.MessageType;
import com.sunlands.deskmate.message.handler.receiver.MessageReceiverFactory;
import com.sunlands.deskmate.message.handler.receiver.Receiver;
import com.sunlands.deskmate.utils.DateUtil;
import com.sunlands.deskmate.utils.IdGenerator;
import com.sunlands.deskmate.vo.CommonResultMessage;
import com.sunlands.deskmate.vo.UserBlacklist;
import com.sunlands.deskmate.vo.response.BusinessResult;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.UUID;
import static com.sunlands.deskmate.message.handler.receiver.impl.PrivateMessageReceiver.RelationShip.*;


/**
 * @author anjunling@sunlands.com
 */
@Slf4j
@Component
public class PrivateMessageReceiver implements Receiver {

    @Autowired
    private DefaultMessageReceiver defaultMessageReceiver;
    @Autowired
    private UserFriendService tzUserFriendService;
    @Lazy
    @Autowired
    private MessageReceiverFactory messageReceiverFactory;

    @Override
    public void receive(Channel channel, Messages message) {
        Long id = IdGenerator.id();
        message.setAckId(id);
        message.setId(id.toString());
        log.info("私聊消息接受 message = {}", message);

        Integer relationShip = isBlackRelationShip(message);
        if (relationShip.equals(FROM_BLACK_LIST.code)
                || relationShip.equals(TO_BLACK_LIST.code)) {
            log.info("用户被拉入黑名单，不能发送消息 message = {}", message);
            Messages msgEntity = Messages.builder()
                    .requestId(UUID.randomUUID().toString())
                    .type(MessageType.BLACK_LIST_LIMIT.getType())
                    .ackId(id)
                    .createTime(DateUtil.getStringDate())
                    .fromUserId(message.getFromUserId())
                    .toId(message.getFromUserId())
                    .message(relationShip.equals(FROM_BLACK_LIST.code) ? "您已经将对方拉入黑名单，无法聊天！" : "对方已拒收您的消息！")
                    .build();
            messageReceiverFactory.getReceiver(MessageType.BLACK_LIST_LIMIT.getType())
                    .receive(channel, msgEntity);
            return;
        }
        defaultMessageReceiver.receive(channel, message);
    }

    /**
     * 1 f
     * @param msgEntity 1被
     */
    private Integer isBlackRelationShip(Messages msgEntity) {
        if (MessageType.PRIVATE_CHAT.getType().equals(msgEntity.getType())) {
            log.debug("checkBlacklist start userId={}, toId={}", msgEntity.getFromUserId(), msgEntity.getToId());
            BusinessResult<List<UserBlacklist>> result = tzUserFriendService.checkBlacklist(Long.valueOf(msgEntity.getFromUserId()), Long.valueOf(msgEntity.getToId()));
            BusinessResult<List<UserBlacklist>> result2 = tzUserFriendService.checkBlacklist(Long.valueOf(msgEntity.getToId()), Long.valueOf(msgEntity.getFromUserId()));
            log.debug("checkBlacklist result={}", result);
            if (result.getCode().equals(CommonResultMessage.SUCCESS.getCode()) && !result.getData().isEmpty()) {
                return result.getData().stream().anyMatch(b -> Long.parseLong(msgEntity.getFromUserId()) == b.getOprationUserId()) ?
                        FROM_BLACK_LIST.code : TO_BLACK_LIST.code;

            } else if (result2.getCode().equals(CommonResultMessage.SUCCESS.getCode()) && !result2.getData().isEmpty()) {
                return result2.getData().stream().anyMatch(b -> Long.parseLong(msgEntity.getFromUserId()) == b.getOprationUserId()) ?
                        FROM_BLACK_LIST.code : TO_BLACK_LIST.code;
            }
        }
        return MUTUAL_NON_BLACK_LIST.code;
    }

    public enum RelationShip {
        MUTUAL_NON_BLACK_LIST(0, "互相不是黑名单"),
        FROM_BLACK_LIST(1, "fromId黑名单中有toId"),
        TO_BLACK_LIST(2, "toId黑名单中有fromId"),
        ;
        public Integer code;
        public String desc;

        RelationShip(Integer code, String desc) {
            this.code = code;
            this.desc = desc;
        }
    }

}
